package com.server.entity;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 服务实例
 */
public class ServiceInstance {

    public static final Logger log = LoggerFactory.getLogger(ServiceInstance.class);

    /**
     * 判断服务实例心跳时间
     */
    public static final Long NOT_ALIVE_TIME = 90 * 1000L;
    /**
     * 服务名称
     */
    private String serviceName;

    /**
     * 主机名
     */
    private String hostName;
    /**
     * 服务实例 id
     */
    private String serviceInstanceId;

    /**
     * 服务ip地址
     */
    private String ip;

    /**
     * 服务端口
     */
    private Integer port;

    /**
     * 服务实例与注册中心的心跳连接
     * 契约
     */
    private Lease lease;

    public ServiceInstance() {
        //续约
        Lease lease = new Lease(System.currentTimeMillis());
        this.lease = lease;
    }

    public String getServiceName() {
        return serviceName;
    }

    public void setServiceName(String serviceName) {
        this.serviceName = serviceName;
    }

    public String getServiceInstanceId() {
        return serviceInstanceId;
    }

    public void setServiceInstanceId(String serviceInstanceId) {
        this.serviceInstanceId = serviceInstanceId;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public Lease getLease() {
        return lease;
    }

    public void setLease(Lease lease) {
        this.lease = lease;
    }

    public String getHostName() {
        return hostName;
    }

    public void setHostName(String hostName) {
        this.hostName = hostName;
    }

    //因为他们是一个整体,采用内部类的方式更为佳
    public class Lease {

        /**
         * 最近一次心跳
         * volatile优化:client服务请求的线程和后台定时检查心跳的线程
         * 存在数据可能不一致,一个线程写,一个线程读
         */
        private volatile Long latestHeartBeatTime;

        /**
         * 更新续约的时间
         */
        public void renew() {
            this.latestHeartBeatTime = System.currentTimeMillis();
            log.info("服务实例[{}]进行了续约,续约时间[{}]", serviceInstanceId, this.latestHeartBeatTime);
        }

        /**
         * 判断当时心跳时间是否存在
         *
         * @return
         */
        public Boolean isAlive() {
            Long currentTime = System.currentTimeMillis();

            if (currentTime - this.latestHeartBeatTime > 90) {
                return false;
            }
            return true;

        }

        public Lease(Long latestHeartBeatTime) {
            this.latestHeartBeatTime = latestHeartBeatTime;
        }

        public Long getLatestHeartBeatTime() {
            return latestHeartBeatTime;
        }

        public void setLatestHeartBeatTime(Long latestHeartBeatTime) {
            this.latestHeartBeatTime = latestHeartBeatTime;
        }
    }

}
